<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 4.2.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">


<link rel="stylesheet" href="/lib/font-awesome/css/font-awesome.min.css">
  <link rel="stylesheet" href="//cdn.jsdelivr.net/gh/fancyapps/fancybox@3/dist/jquery.fancybox.min.css">
  <link rel="stylesheet" href="/lib/pace/pace-theme-minimal.min.css">
  <script src="/lib/pace/pace.min.js"></script>

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"lanqilu.github.io","root":"/","scheme":"Gemini","version":"7.8.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":true},"copycode":{"enable":true,"show_result":true,"style":null},"back2top":{"enable":true,"sidebar":true,"scrollpercent":true},"bookmark":{"enable":false,"color":"#395ca3","save":"auto"},"fancybox":true,"mediumzoom":false,"lazyload":false,"pangu":true,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},"path":"search.xml"};
  </script>

  <meta name="description" content="基于Django官方文档">
<meta property="og:type" content="article">
<meta property="og:title" content="Django">
<meta property="og:url" content="https://lanqilu.github.io/2020/04/06/Python/Django/index.html">
<meta property="og:site_name" content="Halo">
<meta property="og:description" content="基于Django官方文档">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="http://img.whl123456.top/image/%E4%BD%BF%E7%94%A8Pycharm%E5%88%9B%E5%BB%BADjango.png">
<meta property="article:published_time" content="2020-04-06T11:30:08.000Z">
<meta property="article:modified_time" content="2020-08-07T06:16:34.205Z">
<meta property="article:author" content="Lanqilu">
<meta property="article:tag" content="Python">
<meta property="article:tag" content="Django">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="http://img.whl123456.top/image/%E4%BD%BF%E7%94%A8Pycharm%E5%88%9B%E5%BB%BADjango.png">

<link rel="canonical" href="https://lanqilu.github.io/2020/04/06/Python/Django/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>Django | Halo</title>
  
    <script async src="https://www.googletagmanager.com/gtag/js?id=UA-161500949-1"></script>
    <script data-pjax>
      if (CONFIG.hostname === location.hostname) {
        window.dataLayer = window.dataLayer || [];
        function gtag(){dataLayer.push(arguments);}
        gtag('js', new Date());
        gtag('config', 'UA-161500949-1');
      }
    </script>


  <script data-pjax>
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?256151d1651e9d73ec980b2fc69de8f6";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>




  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">Halo</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="menu">
        <li class="menu-item menu-item-home">

    <a href="/" rel="section"><i class="fa fa-fw fa-home"></i>首页</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/tags/" rel="section"><i class="fa fa-fw fa-tags"></i>标签<span class="badge">39</span></a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/categories/" rel="section"><i class="fa fa-fw fa-th"></i>分类<span class="badge">18</span></a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="fa fa-fw fa-archive"></i>归档<span class="badge">85</span></a>

  </li>
        <li class="menu-item menu-item-python">

    <a href="/categories/Python/" rel="section"><i class="fa fa-fw fa-code"></i>Python</a>

  </li>
        <li class="menu-item menu-item-java">

    <a href="/categories/Java/" rel="section"><i class="fa fa-fw fa-code"></i>Java</a>

  </li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup">
        <div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div id="search-result">
  <div id="no-result">
    <i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>
  </div>
</div>

    </div>
  </div>

</div>
    </header>

    
  <div class="reading-progress-bar"></div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://lanqilu.github.io/2020/04/06/Python/Django/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="http://img.whl123456.top/image/avatar.jpg">
      <meta itemprop="name" content="Lanqilu">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Halo">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          Django
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2020-04-06 19:30:08" itemprop="dateCreated datePublished" datetime="2020-04-06T19:30:08+08:00">2020-04-06</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="fa fa-calendar-check-o"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2020-08-07 14:16:34" itemprop="dateModified" datetime="2020-08-07T14:16:34+08:00">2020-08-07</time>
              </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/Python/" itemprop="url" rel="index"><span itemprop="name">Python</span></a>
                </span>
                  ，
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/Python/Django/" itemprop="url" rel="index"><span itemprop="name">Django</span></a>
                </span>
            </span>

          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <div class="note info no-icon">
            <p>基于Django官方文档</p>
          </div>

<a id="more"></a>

<hr>
<h2 id="使用Pycharm创建Django"><a href="#使用Pycharm创建Django" class="headerlink" title="使用Pycharm创建Django"></a>使用Pycharm创建Django</h2><p><img src="http://img.whl123456.top/image/%E4%BD%BF%E7%94%A8Pycharm%E5%88%9B%E5%BB%BADjango.png" alt="使用Pycharm创建Django"></p>
<p>Django项目结构</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">DjangoDemo				 # 根目录只是项目的容器</span><br><span class="line"> ├── db.sqlite3			 # 数据库文件 </span><br><span class="line"> ├── DjangoDemo          # 纯 Python 包</span><br><span class="line"> │   ├── asgi.py         # 作为项目运行在 ASGI 兼容的Web服务器上的入口</span><br><span class="line"> │   ├── wsgi.py         # 作为项目运行在 WSGI 兼容的Web服务器上的入口</span><br><span class="line"> │   ├── settings.py     # Django 项目的配置文件</span><br><span class="line"> │   ├── urls.py         # Django 项目的 URL 声明，就像你网站的“目录”</span><br><span class="line"> │   └── __init__.py</span><br><span class="line"> ├── manage.py           # 一个用各种方式管理 Django 项目的命令行工具</span><br><span class="line"> ├── polls</span><br><span class="line"> └── templates</span><br></pre></td></tr></table></figure>

<p>Django应用结构</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">polls</span><br><span class="line"> ├── admin.py</span><br><span class="line"> ├── apps.py</span><br><span class="line"> ├── migrations</span><br><span class="line"> │   └── __init__.py</span><br><span class="line"> ├── models.py</span><br><span class="line"> ├── tests.py</span><br><span class="line"> ├── views.py</span><br><span class="line"> └── __init__.py</span><br></pre></td></tr></table></figure>

<p>命令行启动项目</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">python manage.py runserver</span><br></pre></td></tr></table></figure>

<h2 id="创建应用视图"><a href="#创建应用视图" class="headerlink" title="创建应用视图"></a>创建应用视图</h2><p>创建视图，打开 <code>polls/views.py</code>，把下面这些 Python 代码输入进去：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> django.http <span class="keyword">import</span> HttpResponse</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">index</span><span class="params">(request)</span>:</span></span><br><span class="line">    <span class="keyword">return</span> HttpResponse(<span class="string">"Hello, world. You're at the polls index."</span>)</span><br></pre></td></tr></table></figure>

<p>如果想看见效果，我们需要将一个 URL 映射到它——这就是我们需要 URLconf 的原因了。</p>
<p>创建 URLconf，在polls中新建<code>urls.py</code>文件</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">polls</span><br><span class="line"> ├── admin.py</span><br><span class="line"> ├── apps.py</span><br><span class="line"> ├── migrations</span><br><span class="line"> │   └── __init__.py</span><br><span class="line"> ├── models.py</span><br><span class="line"> ├── tests.py</span><br><span class="line"> ├── urls.py</span><br><span class="line"> ├── views.py</span><br><span class="line"> └── __init__.py</span><br></pre></td></tr></table></figure>

<p>在<code>urls.py</code>中，输入如下代码：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> django.urls <span class="keyword">import</span> path</span><br><span class="line"></span><br><span class="line"><span class="keyword">from</span> . <span class="keyword">import</span> views</span><br><span class="line"></span><br><span class="line">urlpatterns = [</span><br><span class="line">    path(<span class="string">''</span>, views.index, name=<span class="string">'index'</span>),</span><br><span class="line">]</span><br></pre></td></tr></table></figure>

<p>在根 URLconf 文件中指定我们创建的 <code>polls.urls</code> 模块。在 <code>DjangoDemo/urls.py</code> 文件的 <code>urlpatterns</code> 列表里插入一个 <code>include()</code>， 如下：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> django.contrib <span class="keyword">import</span> admin</span><br><span class="line"><span class="keyword">from</span> django.urls <span class="keyword">import</span> path, include</span><br><span class="line"></span><br><span class="line">urlpatterns = [</span><br><span class="line">    path(<span class="string">'polls/'</span>, include(<span class="string">'polls.urls'</span>)),</span><br><span class="line">    path(<span class="string">'admin/'</span>, admin.site.urls),</span><br><span class="line">]</span><br></pre></td></tr></table></figure>

<p>函数 <a href="https://docs.djangoproject.com/zh-hans/3.0/ref/urls/#django.urls.include" target="_blank" rel="noopener"><code>include()</code></a> 允许引用其它 URLconfs。每当 Django 遇到 <a href="https://docs.djangoproject.com/zh-hans/3.0/ref/urls/#django.urls.include" target="_blank" rel="noopener"><code>include()</code></a> 时，它会截断与此项匹配的 URL 的部分，并将剩余的字符串发送到 URLconf 以供进一步处理。</p>
<p>你现在把 <code>index</code> 视图添加进了 URLconf。通过以下命令验证是否正常工作：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">python manage.py runserver</span><br></pre></td></tr></table></figure>

<p>访问<a href="http://127.0.0.1:8000/polls/而不是http://127.0.0.1:8000" target="_blank" rel="noopener">http://127.0.0.1:8000/polls/而不是http://127.0.0.1:8000</a></p>
<p><code>path()</code>函数</p>
<p><code>path(route, view, [kwargs], [name])</code></p>
<ul>
<li><p><code>route</code>：是一个匹配 URL 的准则（类似正则表达式）。当 Django 响应一个请求时，它会从 <code>urlpatterns</code> 的第一项开始，按顺序依次匹配列表中的项，直到找到匹配的项。这些准则不会匹配 GET 和 POST 参数或域名。例如，URLconf 在处理请求 <code>https://www.example.com/myapp/</code> 时，它会尝试匹配 <code>myapp/</code> 。处理请求 <code>https://www.example.com/myapp/?page=3</code> 时，也只会尝试匹配 <code>myapp/</code>。</p>
</li>
<li><p><code>view</code>：当 Django 找到了一个匹配的准则，就会调用这个特定的视图函数，并传入一个 <a href="https://docs.djangoproject.com/zh-hans/3.0/ref/request-response/#django.http.HttpRequest" target="_blank" rel="noopener"><code>HttpRequest</code></a> 对象作为第一个参数，被“捕获”的参数以关键字参数的形式传入。</p>
</li>
<li><p><code>kwargs</code>：任意个关键字参数可以作为一个字典传递给目标视图函数。</p>
</li>
<li><p><code>name</code>：为你的 URL 取名能使你在 Django 的任意地方唯一地引用它，尤其是在模板中。这个有用的特性允许你只改一个文件就能全局地修改某个 URL 模式。</p>
</li>
</ul>
<h2 id="基础配置"><a href="#基础配置" class="headerlink" title="基础配置"></a>基础配置</h2><p>在 <code>DjangoDemo/settings.py</code> 中</p>
<p>设置域名访问权限</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">myblog&#x2F;settings.py</span><br><span class="line">ALLOWED_HOSTS &#x3D; []      # 修改前</span><br><span class="line">ALLOWED_HOSTS &#x3D; [&#39;*&#39;]   # 修改后，表示任何域名都能访问。如果指定域名的话，在&#39;&#39;里放入指定的域名即可</span><br></pre></td></tr></table></figure>

<hr>
<p>设置TEMPLATES里的’DIRS’，添加模板目录templates的路径，后面我们做网站模板的时候用得着。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"># 修改前</span><br><span class="line">&#39;DIRS&#39;: []</span><br><span class="line"># 修改后</span><br><span class="line">&#39;DIRS&#39;: [os.path.join(BASE_DIR, &#39;templates&#39;)]</span><br><span class="line"># 注：使用pycharm创建的话会自动添加</span><br></pre></td></tr></table></figure>

<hr>
<p>找到DATABASES设置网站数据库类型。这里我们使用默认的sqlite3。如果需要使用Mysql请查看文章：<a href="https://www.django.cn/forum/forum-6.html" target="_blank" rel="noopener">Django如何使用Mysql数据库</a>，其它数据库请查看官方文档。<a href="https://docs.djangoproject.com/en/2.1/ref/settings/#databases" target="_blank" rel="noopener">官方文档</a>，后期上线部署的话，也可以进行数据库与数据库之间的数据转换。具体可查看：<a href="https://www.django.cn/article/show-17.html" target="_blank" rel="noopener">如何把SQLite数据库转换为Mysql数据库</a></p>
<p>在INSTALLED_APPS添加APP应用名称。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">INSTALLED_APPS &#x3D; [                  # Django 的自带应用</span><br><span class="line">    &#39;django.contrib.admin&#39;,         # 管理员站点</span><br><span class="line">    &#39;django.contrib.auth&#39;,          # 认证授权系统。</span><br><span class="line">    &#39;django.contrib.contenttypes&#39;,  # 内容类型框架</span><br><span class="line">    &#39;django.contrib.sessions&#39;,      # 会话框架</span><br><span class="line">    &#39;django.contrib.messages&#39;,      # 消息框架。</span><br><span class="line">    &#39;django.contrib.staticfiles&#39;,   # 管理静态文件的框架</span><br><span class="line">    &#39;polls.apps.PollsConfig&#39;,       # 注册APP应用</span><br><span class="line">]</span><br><span class="line"># 使用pycharm创建的话，这里自动添加</span><br></pre></td></tr></table></figure>

<hr>
<p>修改项目语言和时区</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">myblog&#x2F;settings.py</span><br><span class="line"># 修改前为英文</span><br><span class="line"># LANGUAGE_CODE &#x3D; &#39;en-us&#39;</span><br><span class="line"># 修改后</span><br><span class="line">LANGUAGE_CODE &#x3D; &#39;zh-hans&#39;  # 语言修改为中文</span><br><span class="line"># 时区，修改前</span><br><span class="line"># TIME_ZONE &#x3D; &#39;UTC&#39;</span><br><span class="line"># 修改后</span><br><span class="line">TIME_ZONE &#x3D; &#39;Asia&#x2F;Shanghai&#39;</span><br></pre></td></tr></table></figure>

<hr>
<p>在项目根目录里创建static和media，两个目录。static用来存放模板CSS、JS、图片等静态资源，media用来存放上传的文件，后面我们在讲解数据库创建的时候有说明。</p>
<p>settings里找到STATIC_URL，然后在后面一行加上如下代码。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"># 设置静态文件目录和名称</span><br><span class="line">STATIC_URL &#x3D; &#39;&#x2F;static&#x2F;&#39;</span><br><span class="line"></span><br><span class="line"># 加入下面代码</span><br><span class="line"></span><br><span class="line"># 这个是设置静态文件夹目录的路径</span><br><span class="line">STATICFILES_DIRS &#x3D; (</span><br><span class="line">    os.path.join(BASE_DIR, &#39;static&#39;),</span><br><span class="line">)</span><br><span class="line"># 设置文件上传路径，图片上传、文件上传都会存放在此目录里</span><br><span class="line">MEDIA_URL &#x3D; &#39;&#x2F;media&#x2F;&#39;</span><br><span class="line">MEDIA_ROOT &#x3D; os.path.join(BASE_DIR, &#39;media&#39;)</span><br></pre></td></tr></table></figure>

<p>基本配置完成，更多关于配置文件的介绍，请查看文章：<a href="https://www.django.cn/course/show-10.html" target="_blank" rel="noopener">全局配置settings详解</a></p>
<h2 id="配置数据库"><a href="#配置数据库" class="headerlink" title="配置数据库"></a>配置数据库</h2><p>在 <code>DjangoDemo/settings.py</code> 中</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 默认情况</span></span><br><span class="line">DATABASES = &#123;</span><br><span class="line">    <span class="string">'default'</span>: &#123;</span><br><span class="line">        <span class="string">'ENGINE'</span>: <span class="string">'django.db.backends.sqlite3'</span>,</span><br><span class="line">        <span class="string">'NAME'</span>: os.path.join(BASE_DIR, <span class="string">'db.sqlite3'</span>),</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ul>
<li><p><code>ENGINE</code>：可选值有 <code>&#39;django.db.backends.sqlite3&#39;</code>，<code>&#39;django.db.backends.postgresql&#39;</code>，<code>&#39;django.db.backends.mysql&#39;</code>，或 <code>&#39;django.db.backends.oracle&#39;</code>。其它 <a href="https://docs.djangoproject.com/zh-hans/3.0/ref/databases/#third-party-notes" target="_blank" rel="noopener">可用后端</a>。</p>
</li>
<li><p><code>NAME</code>：数据库的名称。如果使用的是 SQLite，数据库将是你电脑上的一个文件，在这种情况下， <a href="https://docs.djangoproject.com/zh-hans/3.0/ref/settings/#std:setting-NAME" target="_blank" rel="noopener"><code>NAME</code></a> 应该是此文件的绝对路径，包括文件名。默认值 <code>os.path.join(BASE_DIR, &#39;db.sqlite3&#39;)</code> 将会把数据库文件储存在项目的根目录。</p>
</li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">############修改成mysql如下：</span></span><br><span class="line">DATABASES = &#123;</span><br><span class="line">    <span class="string">'default'</span>: &#123;</span><br><span class="line">        <span class="string">'ENGINE'</span>: <span class="string">'django.db.backends.mysql'</span>,</span><br><span class="line">        <span class="string">'NAME'</span>: <span class="string">'test'</span>,    <span class="comment">#你的数据库名称</span></span><br><span class="line">        <span class="string">'USER'</span>: <span class="string">'root'</span>,   <span class="comment">#你的数据库用户名</span></span><br><span class="line">        <span class="string">'PASSWORD'</span>: <span class="string">'445813'</span>, <span class="comment">#你的数据库密码</span></span><br><span class="line">        <span class="string">'HOST'</span>: <span class="string">''</span>, <span class="comment">#你的数据库主机，留空默认为localhost</span></span><br><span class="line">        <span class="string">'PORT'</span>: <span class="string">'3306'</span>, <span class="comment">#你的数据库端口</span></span><br><span class="line">    &#125;&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">#由于mysql默认引擎为MySQLdb，在__init__.py文件中添加下面代码</span></span><br><span class="line"><span class="comment">#在python3中须替换为pymysql,可在主配置文件（和项目同名的文件下，不是app配置文件）中增加如下代码</span></span><br><span class="line"><span class="comment">#import pymysql</span></span><br><span class="line"><span class="comment">#pymysql.install_as_MySQLdb()</span></span><br><span class="line"><span class="comment">#如果找不到pymysql板块，则通过pip install pymysql进行安装。</span></span><br></pre></td></tr></table></figure>

<p>数据库设置好之后，我们就依次输入下面的命令进行数据库迁移：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">python manage.py makemigrations</span><br><span class="line">python manage.py migrate</span><br></pre></td></tr></table></figure>

<p>这个 <a href="https://docs.djangoproject.com/zh-hans/3.0/ref/django-admin/#django-admin-migrate" target="_blank" rel="noopener"><code>migrate</code></a> 命令检查 <a href="https://docs.djangoproject.com/zh-hans/3.0/ref/settings/#std:setting-INSTALLED_APPS" target="_blank" rel="noopener"><code>INSTALLED_APPS</code></a> 设置，为其中的每个应用创建需要的数据表，至于具体会创建什么，这取决于你的 <code>settings.py</code> 设置文件和每个应用的数据库迁移文件。</p>
<h2 id="创建模型"><a href="#创建模型" class="headerlink" title="创建模型"></a>创建模型</h2><p>在这个投票应用中，需要创建两个模型：问题 <code>Question</code> 和选项 <code>Choice</code>。</p>
<p><code>Question</code> 模型包括问题描述和发布时间。<code>Choice</code> 模型有两个字段，选项描述和当前得票数。每个选项属于一个问题。</p>
<p>在<code>models.py</code>文件中写入以下内容：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> django.db <span class="keyword">import</span> models</span><br><span class="line"></span><br><span class="line"><span class="comment"># Create your models here.</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Question</span><span class="params">(models.Model)</span>:</span></span><br><span class="line">    question_text = models.CharField(max_length=<span class="number">200</span>)</span><br><span class="line">    pub_date = models.DateTimeField(<span class="string">'date published'</span>)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Choice</span><span class="params">(models.Model)</span>:</span></span><br><span class="line">    question = models.ForeignKey(Question, on_delete=models.CASCADE)</span><br><span class="line">    choice_text = models.CharField(max_length=<span class="number">200</span>)</span><br><span class="line">    votes = models.IntegerField(default=<span class="number">0</span>)</span><br></pre></td></tr></table></figure>

<p>每个模型被表示为 <a href="https://docs.djangoproject.com/zh-hans/3.0/ref/models/instances/#django.db.models.Model" target="_blank" rel="noopener"><code>django.db.models.Model</code></a> 类的子类。每个模型有许多类变量，它们都表示模型里的一个数据库字段。</p>
<p>每个字段都是 <a href="https://docs.djangoproject.com/zh-hans/3.0/ref/models/fields/#django.db.models.Field" target="_blank" rel="noopener"><code>Field</code></a> 类的实例 - 比如，字符字段被表示为 <a href="https://docs.djangoproject.com/zh-hans/3.0/ref/models/fields/#django.db.models.CharField" target="_blank" rel="noopener"><code>CharField</code></a> ，日期时间字段被表示为 <a href="https://docs.djangoproject.com/zh-hans/3.0/ref/models/fields/#django.db.models.DateTimeField" target="_blank" rel="noopener"><code>DateTimeField</code></a> 。这将告诉 Django 每个字段要处理的数据类型。</p>
<p>每个 <a href="https://docs.djangoproject.com/zh-hans/3.0/ref/models/fields/#django.db.models.Field" target="_blank" rel="noopener"><code>Field</code></a> 类实例变量的名字（例如 <code>question_text</code> 或 <code>pub_date</code> ）也是字段名，所以最好使用对机器友好的格式。你将会在 Python 代码里使用它们，而数据库会将它们作为列名。</p>
<p>你可以使用可选的选项来为 <a href="https://docs.djangoproject.com/zh-hans/3.0/ref/models/fields/#django.db.models.Field" target="_blank" rel="noopener"><code>Field</code></a> 定义一个人类可读的名字。这个功能在很多 Django 内部组成部分中都被使用了，而且作为文档的一部分。如果某个字段没有提供此名称，Django 将会使用对机器友好的名称，也就是变量名。在上面的例子中，我们只为 <code>Question.pub_date</code> 定义了对人类友好的名字。对于模型内的其它字段，它们的机器友好名也会被作为人类友好名使用。</p>
<p>定义某些 <a href="https://docs.djangoproject.com/zh-hans/3.0/ref/models/fields/#django.db.models.Field" target="_blank" rel="noopener"><code>Field</code></a> 类实例需要参数。例如 <a href="https://docs.djangoproject.com/zh-hans/3.0/ref/models/fields/#django.db.models.CharField" target="_blank" rel="noopener"><code>CharField</code></a> 需要一个 <a href="https://docs.djangoproject.com/zh-hans/3.0/ref/models/fields/#django.db.models.CharField.max_length" target="_blank" rel="noopener"><code>max_length</code></a> 参数。这个参数的用处不止于用来定义数据库结构，也用于验证数据，我们稍后将会看到这方面的内容。</p>
<p><a href="https://docs.djangoproject.com/zh-hans/3.0/ref/models/fields/#django.db.models.Field" target="_blank" rel="noopener"><code>Field</code></a> 也能够接收多个可选参数；在上面的例子中：我们将 <code>votes</code> 的 <a href="https://docs.djangoproject.com/zh-hans/3.0/ref/models/fields/#django.db.models.Field.default" target="_blank" rel="noopener"><code>default</code></a> 也就是默认值，设为0。</p>
<p>注意在最后，我们使用 <a href="https://docs.djangoproject.com/zh-hans/3.0/ref/models/fields/#django.db.models.ForeignKey" target="_blank" rel="noopener"><code>ForeignKey</code></a> 定义了一个关系。这将告诉 Django，每个 <code>Choice</code> 对象都关联到一个 <code>Question</code> 对象。Django 支持所有常用的数据库关系：多对一、多对多和一对一。</p>
<h2 id="激活模型"><a href="#激活模型" class="headerlink" title="激活模型"></a>激活模型</h2><p>把 <code>polls</code> 应用安装到我们的项目里，见基础配置</p>
<p>运行下面的命令:</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">python manage.py makemigrations polls</span><br></pre></td></tr></table></figure>

<p>Terminal输出：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">Migrations for &#39;polls&#39;:</span><br><span class="line">  polls\migrations\0001_initial.py</span><br><span class="line">    - Create model Question</span><br><span class="line">    - Create model Choice</span><br></pre></td></tr></table></figure>

<p>通过运行 <code>makemigrations</code> 命令，Django 会检测你对模型文件的修改（在这种情况下，你已经取得了新的），并且把修改的部分储存为一次迁移。</p>
<p>迁移是 Django 对于模型定义（也就是你的数据库结构）的变化的储存形式，它们其实也只是一些你磁盘上的文件。如果你想的话，你可以阅读一下你模型的迁移数据，它被储存在 <code>polls/migrations/0001_initial.py</code> 里。别担心，你不需要每次都阅读迁移文件，但是它们被设计成人类可读的形式，这是为了便于你手动调整Django的修改方式。</p>
<h2 id="Django-管理页面"><a href="#Django-管理页面" class="headerlink" title="Django 管理页面"></a>Django 管理页面</h2><h3 id="创建一个管理员账号"><a href="#创建一个管理员账号" class="headerlink" title="创建一个管理员账号"></a>创建一个管理员账号</h3><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">python manage.py createsuperuser</span><br></pre></td></tr></table></figure>


    </div>

    
    
    
      
  <div class="popular-posts-header">相关文章</div>
  <ul class="popular-posts">
    <li class="popular-posts-item">
      <div class="popular-posts-title"><a href="\2020\03\23\Java\Java书单\" rel="bookmark">计算机书单</a></div>
    </li>
    <li class="popular-posts-item">
      <div class="popular-posts-title"><a href="\2020\03\24\Python\Python网络数据采集\" rel="bookmark">Python网络数据采集</a></div>
    </li>
    <li class="popular-posts-item">
      <div class="popular-posts-title"><a href="\2020\03\27\Python\正则表达式\" rel="bookmark">正则表达式</a></div>
    </li>
    <li class="popular-posts-item">
      <div class="popular-posts-title"><a href="\2019\10\01\Python\函数式编程\" rel="bookmark">函数式编程</a></div>
    </li>
    <li class="popular-posts-item">
      <div class="popular-posts-title"><a href="\2019\10\18\Python\面向对象\" rel="bookmark">面向对象</a></div>
    </li>
  </ul>


      <footer class="post-footer">
          
          <div class="post-tags">
              <a href="/tags/Python/" rel="tag"><i class="fa fa-tag"></i> Python</a>
              <a href="/tags/Django/" rel="tag"><i class="fa fa-tag"></i> Django</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/2020/04/06/Web/JavaScript_BOM/" rel="prev" title="JavaScript BOM">
      <i class="fa fa-chevron-left"></i> JavaScript BOM
    </a></div>
      <div class="post-nav-item">
    <a href="/2020/04/06/Java/Java%E5%AE%B9%E5%99%A8/" rel="next" title="Java容器">
      Java容器 <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#使用Pycharm创建Django"><span class="nav-number">1.</span> <span class="nav-text">使用Pycharm创建Django</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#创建应用视图"><span class="nav-number">2.</span> <span class="nav-text">创建应用视图</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#基础配置"><span class="nav-number">3.</span> <span class="nav-text">基础配置</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#配置数据库"><span class="nav-number">4.</span> <span class="nav-text">配置数据库</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#创建模型"><span class="nav-number">5.</span> <span class="nav-text">创建模型</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#激活模型"><span class="nav-number">6.</span> <span class="nav-text">激活模型</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Django-管理页面"><span class="nav-number">7.</span> <span class="nav-text">Django 管理页面</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#创建一个管理员账号"><span class="nav-number">7.1.</span> <span class="nav-text">创建一个管理员账号</span></a></li></ol></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="Lanqilu"
      src="http://img.whl123456.top/image/avatar.jpg">
  <p class="site-author-name" itemprop="name">Lanqilu</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">85</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
          
        <span class="site-state-item-count">18</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">39</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <a href="https://github.com/lanqilu" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;lanqilu" rel="noopener" target="_blank"><i class="fa fa-fw fa-github"></i></a>
      </span>
      <span class="links-of-author-item">
        <a href="http://mail.qq.com/cgi-bin/qm_share?t=qm_mailme&email=zqKvoL_noruOqKG2o6_nouCtoaM" title="E-Mail → http:&#x2F;&#x2F;mail.qq.com&#x2F;cgi-bin&#x2F;qm_share?t&#x3D;qm_mailme&amp;email&#x3D;zqKvoL_noruOqKG2o6_nouCtoaM" rel="noopener" target="_blank"><i class="fa fa-fw fa-envelope"></i></a>
      </span>
  </div>



      </div>
        <div class="back-to-top motion-element">
          <i class="fa fa-arrow-up"></i>
          <span>0%</span>
        </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 2019 – 
  <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Lanqilu</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.org/" class="theme-link" rel="noopener" target="_blank">NexT.Gemini</a> 强力驱动
  </div>

        








      </div>
    </footer>
  </div>

  
  <script src="/lib/anime.min.js"></script>
  <script src="/lib/pjax/pjax.min.js"></script>
  <script src="//cdn.jsdelivr.net/npm/jquery@3/dist/jquery.min.js"></script>
  <script src="//cdn.jsdelivr.net/gh/fancyapps/fancybox@3/dist/jquery.fancybox.min.js"></script>
  <script src="//cdn.jsdelivr.net/npm/pangu@4/dist/browser/pangu.min.js"></script>
  <script src="/lib/velocity/velocity.min.js"></script>
  <script src="/lib/velocity/velocity.ui.min.js"></script>

<script src="/js/utils.js"></script>

<script src="/js/motion.js"></script>


<script src="/js/schemes/pisces.js"></script>


<script src="/js/next-boot.js"></script>

  <script>
var pjax = new Pjax({
  selectors: [
    'head title',
    '#page-configurations',
    '.content-wrap',
    '.post-toc-wrap',
    '.languages',
    '#pjax'
  ],
  switches: {
    '.post-toc-wrap': Pjax.switches.innerHTML
  },
  analytics: false,
  cacheBust: false,
  scrollTo : !CONFIG.bookmark.enable
});

window.addEventListener('pjax:success', () => {
  document.querySelectorAll('script[data-pjax], script#page-configurations, #pjax script').forEach(element => {
    var code = element.text || element.textContent || element.innerHTML || '';
    var parent = element.parentNode;
    parent.removeChild(element);
    var script = document.createElement('script');
    if (element.id) {
      script.id = element.id;
    }
    if (element.className) {
      script.className = element.className;
    }
    if (element.type) {
      script.type = element.type;
    }
    if (element.src) {
      script.src = element.src;
      // Force synchronous loading of peripheral JS.
      script.async = false;
    }
    if (element.dataset.pjax !== undefined) {
      script.dataset.pjax = '';
    }
    if (code !== '') {
      script.appendChild(document.createTextNode(code));
    }
    parent.appendChild(script);
  });
  NexT.boot.refresh();
  // Define Motion Sequence & Bootstrap Motion.
  if (CONFIG.motion.enable) {
    NexT.motion.integrator
      .init()
      .add(NexT.motion.middleWares.subMenu)
      .add(NexT.motion.middleWares.postList)
      .bootstrap();
  }
  NexT.utils.updateSidebarPosition();
});
</script>




  




  
<script src="/js/local-search.js"></script>













    <div id="pjax">
  

  

  

    </div>
</body>
</html>
